package com.keur.money.utils.dialog

import android.Manifest
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.base.utils.permission.OnPermissionCallback
import com.keur.money.base.utils.permission.XXPermissions
import com.keur.money.databinding.DialogMullaPhotoBinding
import com.keur.money.http.HttpHelper
import com.keur.money.utils.event.KeurEventType
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/12 17:59
 * @Annotation：拍照、相册选择 dialog
 */
class PhotoDialog: ProDialog {
    private lateinit var binding: DialogMullaPhotoBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //选择类型
    private var selectIndex = 1

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    override fun initWindow() {
        val params = window?.attributes
        params?.width =  WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    /**
     * 设置备注
     */
    fun setEventRemark(remark: String){
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogMullaPhotoBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        selectIndex = 1
        checkMullaFlowStateViews()
    }

    override fun initListener() {
        setOnClickListener(R.id.parentLayout)
        setOnClickListener(R.id.imgClose)//关闭
        setOnClickListener(R.id.btnConfirm)//确认
        //拍照
        binding.cameraLayout.setOnClickListener {
            selectIndex = 1
            checkMullaFlowStateViews()
        }
        //相册选择
        binding.albumLayout.setOnClickListener {
            selectIndex = 2
            checkMullaFlowStateViews()
        }
    }

    override fun initData() {

    }

    override fun onViewClick(v: View?) {
        dismiss()
        if (v?.id == R.id.btnConfirm){
            when(selectIndex){
                1 -> {//拍照
                    showMullaFlowCameraClick()
                }
                 else -> {//相册
                    showMullaFlowAlbumClick()
                 }
            }
        }
    }

    /**
     * 切换选择状态
     */
    private fun checkMullaFlowStateViews(){
        binding.cameraLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        binding.textTakePhoto.setTextColor(Color.parseColor("#FF999999"))
        binding.textTakePhoto.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        binding.imgTakePhoto.visibility = View.GONE

        binding.albumLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        binding.textAlbum.setTextColor(Color.parseColor("#FF999999"))
        binding.textAlbum.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        binding.imgAlbum.visibility = View.GONE

        when(selectIndex){
            1 -> {
                binding.cameraLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12_w2)
                binding.textTakePhoto.setTextColor(Color.parseColor("#FF8027FF"))
                binding.textTakePhoto.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                binding.imgTakePhoto.visibility = View.VISIBLE
            }
            else -> {
                binding.albumLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12_w2)
                binding.textAlbum.setTextColor(Color.parseColor("#FF8027FF"))
                binding.textAlbum.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                binding.imgAlbum.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 拍照
     */
    private fun showMullaFlowCameraClick(){
        val permissions = arrayListOf(
            Manifest.permission.CAMERA
        )
        if (XXPermissions.isGranted(context,permissions)){
            mCallback?.openCamera()
        } else {
            val item = JSONObject()
            item.put("isSystem",true)
            item.put("icon", R.mipmap.mulla_permission_camera)
            item.put("permission", Manifest.permission.CAMERA)
            item.put("title", MyApp.context.getString(R.string.permission_camera_title))
            val msgArray = JSONArray()
            val obj1 = JSONObject()
            obj1.put("title", "")
            obj1.put("des", MyApp.context.getString(R.string.permission_camera_desc1))
            msgArray.put(obj1)

            val obj2 = JSONObject()
            obj2.put("title", "")
            obj2.put("des", MyApp.context.getString(R.string.permission_camera_desc2))
            msgArray.put(obj2)

            val obj3 = JSONObject()
            obj3.put("title", "")
            obj3.put("des", MyApp.context.getString(R.string.permission_camera_desc3))
            msgArray.put(obj3)
            item.put("msgList",msgArray)
            showMullaFlowPermissionReasonDialog(item)
        }
    }

    /**
     * 相册
     */
    private fun showMullaFlowAlbumClick(){
        mCallback?.openAlbum()
    }

    interface IDialogCallback {
        //打开相机
        fun openCamera()
        //打开相册
        fun openAlbum()
    }

    /**
     * 权限说明dialog
     */
    private fun showMullaFlowPermissionReasonDialog(data: JSONObject) {
        val reasonDialog = PermissionReasonDialog(context,eventRemark,object: PermissionReasonDialog.IDialogCallback{
            override fun onDenyClick() {
                HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_DENY,data.optString("permission"))
            }
            override fun onAgreeClick() {
                HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_AGREE,data.optString("permission"))
                requestMullaFlowPermission(data)
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showMullaFlowPermissionItem(data)
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(context)
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        mCallback?.openCamera()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    XXPermissions.startPermissionActivity(context,permission)
                }
            })
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addKeurEventAction(KeurEventType.DIALOG.KEUR_DIALOG_PHOTO_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addKeurEventAction(KeurEventType.DIALOG.KEUR_DIALOG_PHOTO_DISMISS,eventRemark)
    }
}